package com.read.utils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class ModelUtils {
	private static final Logger log = LoggerFactory.getLogger(ModelUtils.class);
	public static Object MapToModel(Map<String, String[]> map,Class<?> cla){
		if(map.isEmpty()){
			return null;
		}
		Object obj = null;
		try {
			obj = cla.newInstance();
			Field[] fds = cla.getDeclaredFields();
			Field.setAccessible(fds, true);
			PropertyDescriptor pd = null;
			Method md = null;
			for(Field fd:fds){
				if(map.containsKey(fd.getName())){
					pd = new PropertyDescriptor(fd.getName(),cla);
					md = pd.getWriteMethod();
					String type = fd.getType().getSimpleName();
					String parameter = StringUtils.toString(map.get(fd.getName()));
					switch (type) {
					case "String":
						md.invoke(obj, parameter);
						break;
					case "int":
					case "Integer":
						md.invoke(obj, Integer.parseInt(parameter));
						break;
					case "float":
					case "Float":
						md.invoke(obj, Float.parseFloat(parameter));
						break;
					case "double":
					case "Double":
						md.invoke(obj, Double.parseDouble(parameter));
						break;
					case "Date":
						int i = DateUtils.getFlag(parameter);
						switch (i) {
							case 1:
								md.invoke(obj, DateUtils.parse("yyyy-MM-dd",parameter));
								break;
							case 2:
								md.invoke(obj, DateUtils.parse("yyyy-MM-dd HH:mm:SS",parameter));
								break;
							
							default:
								break;
						}
						break;
					default:
						break;
					}
				}
			}
			
			
			log.debug("组装对象为：{}",JSON.toJSONString(obj));
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
